"""
   ┌─┐       ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│                 │
│       ───       │++ + + +
███████───███████ │+
│                 │+
│       ─┴─       │
│                 │
└───┐         ┌───┘
    │         │
    │         │   + +
    │         │
    │         └──────────────┐
    │                        │
    │                        ├─┐
    │                        ┌─┘
    │                        │
    └─┐  ┐  ┌───────┬──┐  ┌──┘  + + + +
      │ ─┤ ─┤       │ ─┤ ─┤
      └──┴──┘       └──┴──┘  + + + +
             神兽保佑
            代码无BUG!
"""
import cv2
import requests
from fake_useragent import UserAgent
import numpy as np
from operating_sql import SQLManager
import pandas as pd


class DownImg:
    def __init__(self):
        self.sql = SQLManager()
        self.all_img_url = []
        self.headers = {
            "User-Agent": UserAgent().ie
        }

    def get_img_url(self):
        sina_file = pd.read_excel("./file/weibo.xlsx", sheet_name="Sheet1")
        for item in sina_file.values:
            self.all_img_url.append(item)

    def get_sql_img_url(self):
        sql_cx = 'select id,content,img_url from weibo where id >15168'
        self.all_img_url = self.sql.get_tuple_more(sql_cx)

    def down_img(self):
        for img_url_list in self.all_img_url:
            if img_url_list[1] != "" and img_url_list[2] != "":
                for img_url in img_url_list[2].split(","):
                    img_name = str(img_url_list[0]).split(".")[0] + "_" + img_url.split("/")[-1]
                    img_content = requests.get(img_url.strip(), headers=self.headers).content
                    img1 = np.frombuffer(img_content, np.uint8)
                    img_cv = cv2.imdecode(img1, cv2.IMREAD_ANYCOLOR)
                    try:
                        height = int(img_cv.shape[0] / 10 * 9)
                        cropped = img_cv[0:height, 0:img_cv.shape[1]]  # 裁剪坐标为[y0:y1, x0:x1]
                        cv2.imwrite("./new_file/" + img_name, cropped)
                        print(img_name)
                    except:
                        with open("./new_file/" + img_name, "wb") as f:
                            f.write(img_content)
                            print(img_name)

    def run(self):
        self.get_sql_img_url()
        self.down_img()


if __name__ == '__main__':
    d = DownImg()
    d.run()
